function rotate(matrix, direction) {
    var result = [],
        n = matrix.length,
        m = matrix[0].length,
        i, j, row;
    for (i = 0; i < m; ++i) {
        row = [];
        for (j = 0; j < n; ++j) {
            row.push(direction === 'clockwise' ? matrix[n - j - 1][i] : matrix[j][m - i - 1]);
        }
        result.push(row);
    }
    return result;
}

function rotateAgainstClockwise(matrix, times = 1) {
    times = times % 4;
    for (var i = 0; i < times; i++) {
        matrix = rotate(matrix)
    }
    return matrix;
}
